// 子模块moduleA路径：store/modules/moduleA.js 
export default {
	// 开启命名空间
	namespaced: true,
	state: {
		// 购物车
		carList: (uni.getStorageSync('carList')) || [],
		/**
		 * id
		 * image  
		 * title
		 * word
		 * price
		 * count 
		 * state 选中状态
		 * 
		 */ 
	},
	getters: {
		totalState(state) {
			return state.carList.every(v => v.state)
		},
		totalPrice(state) {
			return state.carList.filter(v => v.state)
				.reduce((p, n) => {
					return p + n.price * n.count
				}, 0)
		},
		totalCount(state) {
			return state.carList.reduce((p, n) => {
				return p + n.count
			}, 0)
		}
	},
	mutations: {
		addCar(state, payload) {
			// 1. 验证购物车是否存在该项数据
			const item = state.carList.find(v => v.id === payload.id);
			
			if(item) {
				item.count++
			} else {
				state.carList.unshift(payload)
			}
			
			console.log('addCar', state.carList);
			uni.setStorageSync('carList', (state.carList))
		},
		changeCount(state, payload) {
			const item = state.carList.find(v => v.id === payload.id);
			
			if(item) {
				item.count = payload.count
			}
			
			console.log('changeCount', state.carList);
			uni.setStorageSync('carList', (state.carList))
		},
		changeState(state, payload) {
			const item = state.carList.find(v => v.id === payload.id);
			
			if(item) {
				item.state = !item.state
			}
			
			console.log('changeState', state.carList);
			
			uni.setStorageSync('carList', (state.carList))
		},
		changeAllState(state, payload) {
			state.carList.forEach(v => {
				v.state = payload
			})
			
			uni.setStorageSync('carList', (state.carList))
		}
	},
	actions: { 
		
	}
}
